from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style
from django.templatetags import appmedia
from django.template.loader import render_to_string
from django.conf import settings

class Command(BaseCommand):
    help = ("Prints the https.conf text for the given app(s) to serve up the "
            "static media, to stdout. This should be put in a file which is "
            "included by your main httpd.conf file. Something like "
            "'site_appmedia.conf'.")
    args = '[appname ...]'

    def handle(self, *app_labels, **options):
        if not app_labels:
            self.all=True
            app_labels = appmedia.app_media_apps
        output = []
        for app in app_labels:
            app_output = self.handle_app(app, **options)
            if app_output:
                output.append(app_output)
        return '\n'.join(output)

    def handle_app(self, app, **options):
        self.style = no_style()
        try:
            dir, url = appmedia.get_app_media(app)
        except Exception, e:
            raise CommandError(
                "%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
        if url.startswith('http:') or url.startswith('file:'):
            if self.all: return None
            raise CommandError(
                "App %s uses a site absolute url (%s) which can not be mapped in a .htaccess file" % (app, repr(url))
            )
        if not url.startswith('/'): url = '/' + url
        return render_to_string('appmedia/httpd.conf',
                                { 'dir': dir, 'url': url })
